package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        log.info("page category : {},{}", page, pageSize);

        //1.构建条件构造器和分页对象
        Page<Category> categoryPage = new Page<>(page, pageSize);
        //JSON接受的数据是字符串,需要改成Integer
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();


        //1.5 添加排序条件
        queryWrapper.orderByDesc(Category::getSort);

        //2.查询
        categoryService.page(categoryPage, queryWrapper);
        return R.success(categoryPage);
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info(category.toString());

        //获取当前登录用户的ID
//        Long empId = (Long)request.getSession().getAttribute("employee");

//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
        categoryService.updateById(category);

        return R.success("菜品种类信息修改成功");
    }
    @PostMapping
    public R<String> save( @RequestBody Category category) {
        log.info("新增员工,员工信息为{}", category.toString());
        categoryService.save(category);
        return R.success("新增员工成功");
    }

    @DeleteMapping
    public R<String> delete(Long id) {
        log.info("删除成功,id为{}", id);
        //categoryService.removeById(id);
        categoryService.myRemove(id);
        return R.success("删除成功");
    }

        // 根据条件查询分类数据 Category:分类(找出菜品分类即type为1的)
        @GetMapping("/list")
        public R<List<Category>> list(Category category) {
            //条件构造器
            LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //添加条件
            categoryLambdaQueryWrapper.eq(category.getType()!=null, Category::getType,category.getType());
            //添加排序条件
            categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

            List<Category> categoryList = categoryService.list(categoryLambdaQueryWrapper);
            return R.success(categoryList);
        }

}

